// composables/websocket/useEventWebSocket.js
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { wsProtocol, host } from '@/utils/request/config'

export function useEventWebSocket() {
  let allowReconnect = true
  const socket = ref(null)
  let retryTimer = null
  let retryCount = 0
  const maxRetries = 100
  const baseDelay = 1000
  const socketUrl = `${wsProtocol}//${host}/ws/mouse/event`

  // 关闭 WebSocket 的逻辑
  const closeWebSocket = (ws, code = 1000, reason = '关闭连接') => {
    if (ws && ws.readyState !== WebSocket.CLOSED) {
      ws.close(code, reason)
    }
  }

  // 清理重连定时器
  const clearRetryTimer = () => {
    if (retryTimer) {
      clearTimeout(retryTimer)
      retryTimer = null
    }
  }

  // 断开WebSocket连接
  const closeConnection = () => {
    allowReconnect = false
    retryCount = 0
    clearRetryTimer()
    closeWebSocket(socket.value, 1000, '正常关闭')
    socket.value = null
  }

  // 重连逻辑
  const reconnect = (url) => {
    if (!allowReconnect) return

    if (retryCount >= maxRetries) {
      console.error('WebSocket 重连次数超过限制，停止重连')
      closeConnection()
      return
    }

    clearRetryTimer()

    const delay = Math.min(baseDelay * Math.pow(2, retryCount), 30000)
    console.log(`WebSocket 将在 ${delay / 1000} 秒后尝试第 ${retryCount + 1} 次重连`)

    retryTimer = setTimeout(() => {
      retryCount++
      connect(url)
    }, delay)
  }

  // 建立WebSocket连接
  const connect = (url) => {
    closeWebSocket(socket.value, 1000, '重新连接前关闭')
    socket.value = null

    socket.value = new WebSocket(url)

    socket.value.onopen = () => {
      clearRetryTimer()
      retryCount = 0
      console.log('Event webSocket 连接成功')
    }

    socket.value.onclose = async (event) => {
      console.log('Event webSocket 连接关闭:', event.code, event.reason)
      if (allowReconnect && event.code !== 1000) {
        reconnect(url)
      }
    }

    socket.value.onerror = (error) => {
      console.error('Event webSocket 错误:', error)
    }
  }

  // 发送WebSocket消息
  const sendMessage = (params) => {
    if (socket.value?.readyState === WebSocket.OPEN) {
      const queryString = new URLSearchParams(params).toString()
      socket.value.send(queryString)
    }
  }

  onMounted(() => {
    connect(socketUrl)
  })

  onBeforeUnmount(() => {
    closeConnection()
  })

  return {
    sendWebSocketMessage: sendMessage,
    eventSocketConnect: connect,
    eventCloseWebSocket: closeConnection
  }
}
